//
//  WalletTool.m
//  Bees
//
//  Created by NowYouCanSee on 2018/12/27.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "WalletTool.h"
#import "XHDataBaseManager.h"
#import "LEEAlert.h"
#import "AESCrypt.h"
#import "SignatureViewTool.h"
@implementation WalletTool

SINGLETON_FOR_CLASS(WalletTool)
///dapp操作
+ (void)checkPrivateInputDapp:(DappInfo*)dappInfo signatureModel:(SignatureModel*)signatureModel PasswordWith:(Wallet*)wallet complete:(void(^)(BOOL result,NSString *privateKey,SignatureModel*signatureModel))complete{
  __block BOOL befree=NO;
    ///哦判断在白名单里没有
    [[SignatureViewTool sharedSignatureViewTool]checkSignatureModel:signatureModel withWallet:wallet dapp:dappInfo callBack:^(BOOL isWhite, BOOL isFree,WhiteDappInfo *whiteDappInfo) {
        if (isWhite) {
            signatureModel.isWhite = isWhite;
            signatureModel.whiteDappInfo = whiteDappInfo;
        }
        befree = isFree;
        DLog(@"isWhite %d , isFree %d",isWhite, isFree);
    }];
    if (befree && !ValidStr([[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic objectForKey:wallet.wallet_uid])) {
        [XAlertTool alertTitle:@"提示" message:@"当前操作已经加入了白名单，并且开启了免弹窗设置，授权后，操作会立即执行，是否继续？" cancelAction:^{
            !complete?:complete(NO,nil,signatureModel);
        } sureAction:^{
            [self alertCheckPasswordIsNeedShowUseFingerprint:YES Wallet:wallet complete:^(BOOL result,NSString*pwd) {
                [[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic setObject:pwd forKey:wallet.wallet_uid];;
                !complete?:complete(result,[AESCrypt decrypt:wallet.wallet_private_AES_key password:VALIDATE_STRING(pwd)],signatureModel);
            }];
        }];
        return;
    }
    if (befree && ValidStr([[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic objectForKey:wallet.wallet_uid])) {
        if ([[[[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic objectForKey:wallet.wallet_uid]sha256String]  isEqualToString:wallet.password_sha]) {
            !complete?:complete(YES,[AESCrypt decrypt:wallet.wallet_private_AES_key password:VALIDATE_STRING([[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic objectForKey:wallet.wallet_uid])],signatureModel);
        }
        return;
    }
    
    [[SignatureViewTool sharedSignatureViewTool] alertController:[kAppDelegate getCurrentVC] withSignatureModel:signatureModel DappInfo:dappInfo cancelAction:^{
        !complete?:complete(NO,@"",signatureModel);
    } sureAction:^(WhiteDappInfo*whiteDappInfo,BOOL didWhite) {
        if (ValidStr([[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic objectForKey:wallet.wallet_uid]) && didWhite) {
            if ([[[[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic objectForKey:wallet.wallet_uid]sha256String]  isEqualToString:wallet.password_sha]) {
                !complete?:complete(YES,[AESCrypt decrypt:wallet.wallet_private_AES_key password:VALIDATE_STRING([[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic objectForKey:wallet.wallet_uid])],signatureModel);
                if (whiteDappInfo) {
                    [[SignatureViewTool sharedSignatureViewTool]addWhiteDappInfo:whiteDappInfo withWallet:wallet dapp:dappInfo];
                }
            }
        }else{
            if ([self isUseFingerprintCurrentWallet:wallet] && ![self sharedWalletTool].useSelfInput) {
                [self touchVerificationComplete:^(TDTouchIDState state) {
                    if (state == TDTouchIDStateSuccess) {
                        if (![self sharedWalletTool].useFingerprint && [self sharedWalletTool].isSetFingerprint) {
                            [[self sharedWalletTool].walletUseFingerprint removeObjectForKey:wallet.wallet_uid];
                        }
                        if (whiteDappInfo) {
                            [[SignatureViewTool sharedSignatureViewTool]addWhiteDappInfo:whiteDappInfo withWallet:wallet dapp:dappInfo];
                        }
                        !complete?:complete(YES,[AESCrypt decrypt:wallet.wallet_private_AES_key password:VALIDATE_STRING([[self sharedWalletTool].walletUseFingerprint objectForKey:wallet.wallet_uid]?:@"")],signatureModel);
                    }else if(state == TDTouchIDStateInputPassword){
                        [self alertCheckPasswordIsNeedShowUseFingerprint:YES Wallet:wallet complete:^(BOOL result,NSString*pwd) {
                            if (result) {
                                if (signatureModel.isWhite) {
                                    [[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic setObject:pwd forKey:wallet.wallet_uid];;
                                }
                                if (whiteDappInfo) {
                                    [[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic setObject:pwd forKey:wallet.wallet_uid];;
                                    [[SignatureViewTool sharedSignatureViewTool]addWhiteDappInfo:whiteDappInfo withWallet:wallet dapp:dappInfo];
                                }
                                !complete?:complete(result,[AESCrypt decrypt:wallet.wallet_private_AES_key password:VALIDATE_STRING(pwd)],signatureModel);
                            }
                        }];
                    }else if (state == TDTouchIDStateTouchIDLockout){
                        [XAlertTool alertTitle:kIsIphoneX?XLocalized(@"FaceID 被锁定(连续多次验证FaceID失败,系统需要您手动输入密码)"):XLocalized(@"TouchID 被锁定(连续多次验证TouchID失败,系统需要您手动输入密码)") message:nil cancelAction:^{
                        } sureAction:^{
                            [self alertCheckPasswordIsNeedShowUseFingerprint:YES Wallet:wallet complete:^(BOOL result,NSString*pwd) {
                                if (result) {
                                    if (signatureModel.isWhite) {
                                        [[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic setObject:pwd forKey:wallet.wallet_uid];;
                                    }
                                    if (whiteDappInfo) {
                                        [[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic setObject:pwd forKey:wallet.wallet_uid];;
                                        [[SignatureViewTool sharedSignatureViewTool]addWhiteDappInfo:whiteDappInfo withWallet:wallet dapp:dappInfo];
                                    }
                                    !complete?:complete(result,[AESCrypt decrypt:wallet.wallet_private_AES_key password:VALIDATE_STRING(pwd)],signatureModel);
                                }
                            }];
                        }];
                    }else if(state ==TDTouchIDStateNotSupport){
                        [self alertCheckPasswordIsNeedShowUseFingerprint:YES Wallet:wallet complete:^(BOOL result,NSString*pwd) {
                            if (result) {
                                if (signatureModel.isWhite) {
                                    [[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic setObject:pwd forKey:wallet.wallet_uid];;
                                }
                                if (whiteDappInfo) {
                                    [[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic setObject:pwd forKey:wallet.wallet_uid];;
                                    [[SignatureViewTool sharedSignatureViewTool]addWhiteDappInfo:whiteDappInfo withWallet:wallet dapp:dappInfo];
                                }
                                !complete?:complete(result,[AESCrypt decrypt:wallet.wallet_private_AES_key password:VALIDATE_STRING(pwd)],signatureModel);
                            }
                        }];
                    }else{
                        !complete?:complete(NO,@"",signatureModel);
                    }
                }];
                return;
            }
            
            [self alertCheckPasswordIsNeedShowUseFingerprint:YES Wallet:wallet complete:^(BOOL result,NSString*pwd) {
                if (result) {
                    if (signatureModel.isWhite) {
                        [[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic setObject:pwd forKey:wallet.wallet_uid];;
                    }
                    if (whiteDappInfo) {
                        [[SignatureViewTool sharedSignatureViewTool].curWalletPwdDic setObject:pwd forKey:wallet.wallet_uid];;
                        [[SignatureViewTool sharedSignatureViewTool]addWhiteDappInfo:whiteDappInfo withWallet:wallet dapp:dappInfo];
                    }
                    !complete?:complete(result,[AESCrypt decrypt:wallet.wallet_private_AES_key password:VALIDATE_STRING(pwd)],signatureModel);
                }
            }];
        }
       
    }];

}
+ (NSString*)decryptWallet:(Wallet*)wallet password:(NSString*)password{
    return [AESCrypt decrypt:wallet.wallet_private_AES_key password:VALIDATE_STRING(password)];
}
+ (NSString*)encryptWalletPrivatekey:(NSString*)Privatekey password:(NSString*)password{
    return [AESCrypt encrypt:Privatekey password:VALIDATE_STRING(password)];
}
+ (void)checkPrivateInputPasswordWith:(Wallet*)wallet complete:(void(^)(BOOL result,NSString *privateKey))complete{
    [self alertCheckPasswordIsNeedShowUseFingerprint:YES Wallet:wallet complete:^(BOOL result,NSString*pwd) {
        !complete?:complete(result,[AESCrypt decrypt:wallet.wallet_private_AES_key password:VALIDATE_STRING(pwd)]);
    }];
}

+ (void)checkInputPasswordWith:(Wallet*)wallet complete:(ResultBlock)complete{
    [self sharedWalletTool].useSelfInput = YES;
    [self alertCheckPasswordIsNeedShowUseFingerprint:NO Wallet:wallet complete:^(BOOL result,NSString*pwd) {
        [self sharedWalletTool].useSelfInput = NO;
        !complete?:complete(result,pwd);
    }];
}

+ (void)setCurrentWallet:(nullable Wallet *)wallet{
    CHANGE_CURRENT_WALLET_ID(wallet.wallet_uid);
}
+ (void)changeCurrentWallet{
    Wallet*currentW = [[[XHDataBaseManager shareInstance]selectAllLocalWallet] objectOrNilAtIndex:0];
    CHANGE_CURRENT_WALLET_ID(currentW.wallet_uid);
}
+ (void)useFingerprintCurrentWallet:(Wallet *)wallet complete:(ResultBlock)complete{
    if (![self canUseTouchID]) {
        [kCurrentVC.view makeToast: kIsIphoneX?XLocalized(@"当前设备不支持FaceID, 请使用密码"):XLocalized(@"当前设备不支持TouchID, 请使用密码") duration:2.0 position:CSToastPositionCenter];
        !complete?:complete(NO,@"");
        return;
    }
    [self sharedWalletTool].useFingerprint = YES;
    [self sharedWalletTool].isSetFingerprint = YES;
    [self alertCheckPasswordIsNeedShowUseFingerprint:NO Wallet:wallet complete:^(BOOL result,NSString*pwd) {
        [self sharedWalletTool].isSetFingerprint = NO;
        !complete?:complete(result,pwd);
    }];
}
+ (void)unUseFingerprintCurrentWallet:(Wallet *)wallet complete:(ResultBlock)complete{
    [self sharedWalletTool].useFingerprint = NO;
    [self sharedWalletTool].isSetFingerprint = YES;
    [self alertCheckPasswordIsNeedShowUseFingerprint:NO Wallet:wallet complete:^(BOOL result,NSString*pwd) {
        [self sharedWalletTool].isSetFingerprint = NO;
        !complete?:complete(result,pwd);
    }];
}

+ (void)alertCheckPasswordIsNeedShowUseFingerprint:(BOOL)needUseFingerprint Wallet:(Wallet*)wallet complete:(ResultBlock)complete{
    if ([self isUseFingerprintCurrentWallet:wallet] && ![self sharedWalletTool].useSelfInput) {
        [self touchVerificationComplete:^(TDTouchIDState state) {
            if (state == TDTouchIDStateSuccess) {
                if (![self sharedWalletTool].useFingerprint && [self sharedWalletTool].isSetFingerprint) {
                    [[self sharedWalletTool].walletUseFingerprint removeObjectForKey:wallet.wallet_uid];
                }
                !complete?:complete(YES,[[self sharedWalletTool].walletUseFingerprint objectForKey:wallet.wallet_uid]?:@"");
            }else if(state == TDTouchIDStateInputPassword){
                [self checkInputPasswordWith:wallet complete:^(BOOL result,NSString*pwd) {
                    !complete?:complete(result,pwd);
                }];
            }else if (state == TDTouchIDStateTouchIDLockout){
                [XAlertTool alertTitle:kIsIphoneX?XLocalized(@"FaceID 被锁定(连续多次验证FaceID失败,系统需要您手动输入密码)"):XLocalized(@"TouchID 被锁定(连续多次验证TouchID失败,系统需要您手动输入密码)") message:nil cancelAction:^{
                } sureAction:^{
                    [self checkInputPasswordWith:wallet complete:^(BOOL result, NSString * _Nonnull pwd) {
                        !complete?:complete(result,pwd);
                    }];
                }];
            }else if(state ==TDTouchIDStateNotSupport){
                [self checkInputPasswordWith:wallet complete:^(BOOL result, NSString * _Nonnull pwd) {
                    !complete?:complete(result,pwd);
                }];
            }else{
                !complete?:complete(NO,@"");
            }
        }];
        return;
    }
  
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, AdaptedWidth(150), 35)];
    [btn setImage:IMAGE_NAMED(@"corner_unselect") forState:UIControlStateNormal];
    [btn setImage:IMAGE_NAMED(@"corner_select") forState:UIControlStateSelected];
    [btn setTitle:kIsIphoneX?XLocalized(@"使用面容识别代替密码"):XLocalized(@"使用指纹识别代替密码") forState:UIControlStateNormal];
    [btn setTitleColor:kColorMain forState:UIControlStateNormal];
    btn.titleLabel.font = kDefaultFont(13);
    [btn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:5];
    [btn addTapBlock:^(UIButton * _Nonnull btn) {
        btn.selected = !btn.selected;
    }];
    __block UITextField * inputTF;
    [LEEAlert alert].config
    .LeeHeaderInsets(UIEdgeInsetsMake(20, 20, 10, 20))
    .LeeTitle(XLocalized(@"验证密码"))
    .LeeItemInsets(UIEdgeInsetsMake(0, 0, 15, 0))
    .LeeMaxWidth(kScreenWidth-AdaptedWidth(100))
    .LeeAddTextField(^(UITextField *textField) {
        textField.borderStyle = UITextBorderStyleNone;
        textField.backgroundColor = UIColorHex(#F7F7F7);
        textField.textColor = UIColorHex(333333);
        ViewRadius(textField, textField.height*.5);
        UIView*leftV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, textField.height)];
        textField.leftView= leftV;
        textField.leftViewMode = UITextFieldViewModeAlways;
        UIView*rightV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, textField.height)];
        textField.rightView= rightV;
        textField.leftViewMode = UITextFieldViewModeAlways;
        textField.placeholder = XLocalized(@"请输入密码");
        textField.font = kDefaultFont(17);
        textField.secureTextEntry = YES;
        inputTF = textField;
    }).LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0))

   
    .LeeAddCustomView(^(LEECustomView *custom) {
        if (needUseFingerprint && ![self isUseFingerprintCurrentWallet:wallet] && [self canUseTouchID]) {
            custom.view = btn;
            custom.positionType = LEECustomViewPositionTypeCenter;
        }
    })
    .LeeAddAction(^(LEEAction *action) {
        action.type = LEEActionTypeCancel;
        action.title = XLocalized(@"取消");
        action.titleColor = kTitleColor;
        action.font = kBoldFont(17);
        action.backgroundColor = [UIColor whiteColor];
        action.clickBlock = ^{
            !complete?:complete(NO,@"");
        };
    })
    .LeeItemInsets(UIEdgeInsetsMake(0, 0, 0, 0)) // 想为哪一项设置间距范围 直接在其后面设置即可 ()
    .LeeAddAction(^(LEEAction *action) {
        action.type = LEEActionTypeDefault;
        action.isClickNotClose = YES;
        action.title = XLocalized(@"确定");
        action.titleColor = kColorMain;
        action.font = kBoldFont(17);
        action.backgroundColor = [UIColor whiteColor];
        action.clickBlock = ^{
            // 删除点击事件Block
            if (!inputTF.text.length) {
                [[LEEAlert getAlertWindow] makeToast: XLocalized(@"请输入密码") duration:2.0 position:CSToastPositionTop];
                return;
            }
            if ([[inputTF.text sha256String] isEqualToString:wallet.password_sha]) {
                [LEEAlert closeWithCompletionBlock:^{
                    if (btn.selected && needUseFingerprint) {
                        [self sharedWalletTool].walletPwd = inputTF.text;
                        [[self sharedWalletTool].walletUseFingerprint setObject:inputTF.text forKey:wallet.wallet_uid];
                    }
                    if ([self sharedWalletTool].isSetFingerprint) {
                        if ([self sharedWalletTool].useFingerprint) {
                            [self sharedWalletTool].walletPwd = inputTF.text;
                            //                        [self touchVerificationComplete:^(TDTouchIDState state) {
                            //                            if (state == TDTouchIDStateSuccess) {
                            [self touchVerificationComplete:^(TDTouchIDState state) {
                                if (state == TDTouchIDStateSuccess) {
                                    [kCurrentVC.view makeToast: XLocalized(@"设置成功") duration:2.0 position:CSToastPositionTop];
                                    [[self sharedWalletTool].walletUseFingerprint setObject:inputTF.text forKey:wallet.wallet_uid];
                                }else{
                                    !complete?:complete(NO,inputTF.text);
                                }
                            }];
                            //                                !complete?:complete(YES);
                            //                            }else if(state ==TDTouchIDStateInputPassword){
                            //                                [kAppWindow makeToast: XLocalized(@"您已取消验证") duration:2.0 position:CSToastPositionTop];
                            //                                !complete?:complete(NO);
                            //                            }else{
                            //                                !complete?:complete(NO);
                            //                            }
                            //                        }];
                        }else{
                            [self sharedWalletTool].walletPwd = @"";
                            [[self sharedWalletTool].walletUseFingerprint removeObjectForKey:wallet.wallet_uid];
                        }
                    }
                    !complete?:complete(YES,inputTF.text);
                    
                }];
            }else{
                if (CURRENT_WALLET.password_tip.length) {
                     [[LEEAlert getAlertWindow] makeToast:[NSString stringWithFormat:@"%@\n%@", XLocalized(@"密码输入不正确"),CURRENT_WALLET.password_tip] duration:3.0 position:CSToastPositionTop];
                }else{
                    [[LEEAlert getAlertWindow] makeToast: XLocalized(@"密码输入不正确，请重新输入") duration:2.0 position:CSToastPositionTop];
                }
                inputTF.text = @"";
            }
        };
    })
    .LeeHeaderColor([UIColor whiteColor])
    .LeePriority(1000)
//    .LeeQueue(YES) // 添加到队列
    .LeeShow();
    
}

+(BOOL)isUseFingerprintCurrentWallet:(Wallet *)wallet{
    return !IsNilOrNull([[WalletTool sharedWalletTool].walletUseFingerprint objectForKey:wallet.wallet_uid]);
}


- (NSMutableDictionary*) walletUseFingerprint{
    if (!_walletUseFingerprint) {
        _walletUseFingerprint =[NSMutableDictionary dictionary];
    }
    return _walletUseFingerprint;
}

/**
 验证 TouchID & FaceID
 */
+ (void)touchVerificationComplete:(void(^)(TDTouchIDState state))complete {
    
    [TDTouchID td_showTouchIDWithDescribe:nil BlockState:^(TDTouchIDState state, NSError *error) {
        if (state == TDTouchIDStateSuccess) {
            !complete?:complete(TDTouchIDStateSuccess);
        }else if(state == TDTouchIDStateInputPassword){
            !complete?:complete(TDTouchIDStateInputPassword);
        }else if(state == TDTouchIDStateTouchIDLockout){
            !complete?:complete(TDTouchIDStateTouchIDLockout);
        }else if(state== TDTouchIDStateNotSupport){
            !complete?:complete(TDTouchIDStateNotSupport);
        }else{
            !complete?:complete(TDTouchIDStateFail);
        }
//        if (state == TDTouchIDStateNotSupport) {    //不支持TouchID
//            [kAppWindow makeToast: kIsIphoneX?XLocalized(@"当前设备不支持FaceID, 请使用密码"):XLocalized(@"当前设备不支持TouchID, 请使用密码") duration:2.0 position:CSToastPositionTop];
//            !complete?:complete(TDTouchIDStateNotSupport);
//        } else if (state == TDTouchIDStateSuccess) {
//            //TouchID验证成功
//            !complete?:complete(TDTouchIDStateSuccess);
//        } else if (state == TDTouchIDStateInputPassword) { //用户选择手动输入密码
//            [kAppWindow makeToast: kIsIphoneX?XLocalized(@"当前设备不支持FaceID, 请使用密码"):XLocalized(@"当前设备不支持TouchID, 请使用密码") duration:2.0 position:CSToastPositionTop];
//            !complete?:complete(TDTouchIDStateInputPassword);
//        }else if(state == TDTouchIDStateUserCancel){
//            [kAppWindow makeToast: XLocalized(@"您已取消验证") duration:2.0 position:CSToastPositionTop];
//            !complete?:complete(TDTouchIDStateUserCancel);
//        }else{
//            [kAppWindow makeToast: XLocalized(error.localizedDescription) duration:2.0 position:CSToastPositionTop];
//            !complete?:complete(TDTouchIDStateFail);
//        }

    }];
}

+ (BOOL)canUseTouchID{
    return [TDTouchID canUseTouchID];
}


@end
